package com.smart.car.auth.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类：包含了生成和解析token
 *
 * @author zoutao.blog.csdn.net
 * @date 2021-04-29
 */
public class JwtUtils {
    /**
     * 私钥加密token
     * 采用RS256加密算法。
     * @param map           JWT载荷中的数据
     * @param expireMinutes 过期时间，单位分钟(时间单位可以从这里更换)
     * @throws Exception
     */
    public static String generateToken(Map<String, Object> map, PrivateKey key, int expireMinutes) throws Exception {
        return Jwts.builder()
                .setClaims(map)
                //往后移动n分钟，这里已经定义了单位是分钟，就不需要写*60
                .setExpiration(DateUtil.offset(DateUtil.date(), DateField.MINUTE,expireMinutes).toSqlDate())
                .signWith(key, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token 用户请求中的token
     * @throws Exception
     */
    private static Jws<Claims> parserToken(String token, PublicKey key) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token);
    }

    /**
     * 获取token中的用户信息
     *
     * @param token 用户请求中的令牌
     * @return 用户信息
     */
    public static Map<String, Object> getInfoFromToken(String token, PublicKey key) {
        HashMap<String, Object> map = new HashMap<>(16);
        try {
            Jws<Claims> claimsJws = parserToken(token, key);
            return claimsJws.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains("JWT expired")) {
                map.put("code:",500);
                map.put("msg:","认证过期");
            } else {
                map.put("code:",502);
                map.put("msg:","认证失败");
            }
            return map;
        }
    }

    /* 测试解析token */
    public static void main(String[] args) throws Exception {
//        PublicKey publicKey = RsaUtils.getPublicKey("E://rsa//rsa.pub");
//        Jws<Claims> claimsJws = parserToken("eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyX2lkIjoxMjczOTEyMTE1MDI3MTE2MDMyLCJ1c2VyX3JvbGUiOjAsImV4cCI6MTU5MzMxODM2OH0.FqXgDP6b3qoTrAXteCHxQ2IUnryh_7XfeUHPTW8bXiLpXVDn1zigBJTGcxFhivcy0aIACBs32i0ynbBc5DUli6chesvIE7HfbAl9IiBj0D6Ujde-HnQdHcrzjPt783fy-5Voj4HJZWHrAH9SCPkKqs6VUUR6Ba8QHJeoJtkmUXg", publicKey);
//        System.out.println(claimsJws.getSignature());
//        System.out.println(claimsJws.toString());
//        System.out.println(publicKey);


        DateTime offset = DateUtil.offset(DateUtil.date(), DateField.MINUTE, 30);
        System.out.println(DateUtil.date());
        System.out.println(offset);






    }
}
